﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace RecipeManager
{
    public partial class RecipeForm : Form
    {
        private Recipe _currentRecipe = null;
        public Recipe CurrentRecipe
        {
            get
            {
                return _currentRecipe;
            }
            set
            {
                if (value != null)
                {
                    _currentRecipe = value;
                }
                else
                {
                    _currentRecipe = new Recipe();
                }

                RecipeBindingSource.DataSource = CurrentRecipe;
            }
        }

        public RecipeForm()
        {
            InitializeComponent();
        }

        public RecipeForm(Recipe recipe)
            : this()
        {
            CurrentRecipe = recipe;
        }

        private void _butPreparationEditor_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this,
                                "Zusatzinformationen gehen verloren. Wollen Sie fortfahren?",
                                "Fortfahren?",
                                MessageBoxButtons.YesNoCancel,
                                MessageBoxIcon.Question,
                                MessageBoxDefaultButton.Button1) != DialogResult.Yes)
            {
                return;
            }

            string data = "";
            CurrentRecipe.Preparation.ConvertAll(x => x.Description).ToList().ForEach(x => data = data + "* " + x + Environment.NewLine);
            PreparationEditorData text = new PreparationEditorData(data);
            if ((new PreparationForm(text).ShowDialog(this)) == DialogResult.OK)
            {
                StringReader reader = new StringReader(text.Data);
                string line = "";

                CurrentRecipe.Preparation.Clear();

                while ((line = reader.ReadLine()) != null)
                {
                    if ((CurrentRecipe.Preparation.Count == 0) || (line.Trim().StartsWith("*")))
                    {
                        CurrentRecipe.Preparation.Add(new RecipePreparation() { Description = line.Substring(1).Trim(), AdditionalInfo = "" });
                    }
                    else
                    {
                        CurrentRecipe.Preparation[CurrentRecipe.Preparation.Count - 1].Description += (Environment.NewLine + line);
                    }
                }

                preparationBindingSource.ResetBindings(false);

            }

        }

    }
}
